package com.tbq.game.service.socket.netty

import io.netty.buffer.Unpooled
import io.netty.channel.ChannelInitializer
import io.netty.channel.socket.SocketChannel
import io.netty.handler.codec.DelimiterBasedFrameDecoder
import io.netty.handler.codec.string.StringDecoder
import io.netty.handler.codec.string.StringEncoder
import io.netty.handler.timeout.IdleStateHandler
import io.netty.util.CharsetUtil
import java.nio.charset.Charset
import java.util.concurrent.TimeUnit

class ClientInitializer: ChannelInitializer<SocketChannel>() {
    override fun initChannel(ch: SocketChannel?) {
        val pipeline = ch?.pipeline()
        val delimiter = Unpooled.copiedBuffer(NettyClient.endFlag, Charset.forName("UTF-16LE"))
        // 当达到最大长度仍没找到分隔符 就抛出异常
        // ch.pipeline().addLast(new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, true, false, delimiter));
        ch?.pipeline()?.addLast(DelimiterBasedFrameDecoder(Integer.MAX_VALUE, delimiter))
        //心跳
        pipeline?.addLast("idleStateHandler", IdleStateHandler(
            NettyClient.readerIdleTime.toLong(),
            NettyClient.writerIdleTime.toLong(), NettyClient.allIdleTime.toLong(),TimeUnit.SECONDS))
        pipeline?.addLast(StateCheckChannelHandler())
        //解码、编码
        pipeline?.addLast("decoder", StringDecoder(CharsetUtil.UTF_16LE))
        pipeline?.addLast("encoder", StringEncoder(CharsetUtil.UTF_16LE))
        pipeline?.addLast("handler", ClientHandler())
    }
}